<template>
	<view class="container">
		<view class="header-top">就近加油</view>
		<view class="search-bar-wrapper">
			<view class="search-bar">
				<input type="text" placeholder="输入需要搜索的内容" class="search-input" v-model="searchQuery" />
				<img src="/static/whb/搜索@3x.png" alt="搜索图标" class="search-icon" />
			</view>
			<view class="map-mode-btn" @click="map">地图模式</view>
		</view>
		<view class="gasoline-types">
			<view v-for="(type, index) in gasolineTypes" :key="index"
				:class="['gasoline-type', { selected: selectedType === index }]" @click="selectType(index)">
				{{ type }}#
			</view>
		</view>
		<view class="gas-station-list">
			<view v-for="(station, index) in filteredGasStations" :key="index" class="gas-station-item">
				<img :src="station.image" alt="加油站图片" class="gas-station-image" />
				<view class="gas-station-info">
					<view class="name-row">
						<view class="name" @click="goToStoreDetail(station)">{{ station.name }}</view>
						<view class="distance">{{ station.distance }}m</view>
					</view>
					<view class="discount">
						<view v-if="station.discount200" class="discount-tag">满200减20</view>
						<view v-if="station.discount500" class="discount-tag">满500减60</view>
					</view>
					<view class="business-hours">营业时间：{{ station.businessHours }}</view>
					<view class="price">￥{{ station.price }}/升</view>
					<view class="address">{{ station.address }}</view>
					<image src="/static/whb/plane@3x.png" class="tiaozhuan" @click="goToMap(station)"></image>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		computed
	} from 'vue';

	// 汽油标号数组
	const gasolineTypes = ref([]);
	const selectedType = ref(0);
	const gasStations = ref([]);
	const userLocation = ref({
		longitude: null,
		latitude: null
	});

	const searchQuery = ref('');

	const filteredGasStations = computed(() => {
		const query = searchQuery.value.toLowerCase();
		if (!query) {
			return gasStations.value;
		}
		return gasStations.value.filter(station => {
			return station.name.toLowerCase().includes(query);
		});
	});

	// 页面加载时获取汽油标号和用户位置
	onMounted(() => {
		getUserLocation();
	});

	// 获取用户当前位置
	function getUserLocation() {
		uni.getLocation({
			type: 'wgs84',
			success: (res) => {
				userLocation.value = {
					longitude: res.longitude,
					latitude: res.latitude
				};
				fetchGasolineTypes();
			},
			fail: (error) => {
				console.error('获取位置失败:', error);
				uni.showToast({
					title: '获取位置失败',
					icon: 'none'
				});
				fetchGasolineTypes();
			}
		});
	}

	// 计算两个坐标点之间的距离(米) - Haversine公式
	function calculateDistance(lat1, lon1, lat2, lon2) {
		const R = 6371e3; // 地球半径(米)
		const φ1 = lat1 * Math.PI / 180; // 纬度，转为弧度
		const φ2 = lat2 * Math.PI / 180;
		const Δφ = (lat2 - lat1) * Math.PI / 180;
		const Δλ = (lon2 - lon1) * Math.PI / 180;

		const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
			Math.cos(φ1) * Math.cos(φ2) *
			Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
		const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

		return Math.round(R * c); // 四舍五入到整数米
	}

	// 调用后端接口获取汽油种类
	function fetchGasolineTypes() {
		uni.request({
			url: 'http://localhost:9401/CarGesType/list',
			method: 'GET',
			header: {
				'Authorization': uni.getStorageSync('Token')
			},
			success: (res) => {
				if (res.data.code === 200) {
					gasolineTypes.value = res.data.rows.map(item => item.name);
					fetchGasStationsByType(0);
				} else {
					uni.showToast({
						title: '获取汽油标号失败',
						icon: 'none'
					});
					fetchGasStationsByType(0);
				}
			},
			fail: (error) => {
				console.error('网络请求失败:', error);
				uni.showToast({
					title: '网络请求失败，请重试',
					icon: 'none'
				});
				fetchGasStationsByType(0);
			}
		});
	}

	// 根据汽油类型获取加油站
	function fetchGasStationsByType(typeIndex) {
		if (gasolineTypes.value.length === 0 && typeIndex !== 0) {
			uni.showToast({
				title: '汽油类型未加载，请稍后再试或下拉刷新',
				icon: 'none'
			});
			return;
		}

		const gasTypeId = typeIndex + 1;

		uni.request({
			url: `http://localhost:9401/GesStation/listByGasType/${gasTypeId}`,
			method: 'GET',
			header: {
				'Authorization': uni.getStorageSync('Token')
			},
			success: (res) => {
				if (res.data.code === 200) {
					let stations = res.data.rows.map(station => {
						// 转换坐标字符串为数字
						const stationLng = parseFloat(station.longitude);
						const stationLat = parseFloat(station.latitude);

						// 计算距离
						let distance = 0;
						if (userLocation.value.longitude && userLocation.value.latitude &&
							!isNaN(stationLng) && !isNaN(stationLat)) {
							distance = calculateDistance(
								userLocation.value.latitude,
								userLocation.value.longitude,
								stationLat,
								stationLng
							);
						}

						return {
							id: station.id,
							image: station.img,
							name: station.name,
							distance: distance,
							longitude: stationLng,
							latitude: stationLat,
							discount200: true,
							discount500: true,
							businessHours: station.week,
							price: null, // 先设为null，后面单独获取
							address: station.address,
							gasTypeId: gasTypeId // 保存当前油类型ID
						};
					});

					// 按距离排序
					stations.sort((a, b) => a.distance - b.distance);

					gasStations.value = stations;

					// 为每个加油站获取价格
					stations.forEach(station => {
						fetchGasPrice(station.id, gasTypeId, stations.indexOf(station));
					});
				} else {
					uni.showToast({
						title: '获取加油站列表失败',
						icon: 'none'
					});
				}
			},
			fail: (error) => {
				console.error('网络请求失败:', error);
				uni.showToast({
					title: '网络请求失败，请重试',
					icon: 'none'
				});
			}
		});
	}
	
	//油价
	function fetchGasPrice(stationId, gasTypeId, index) {
	  uni.request({
	    url: `http://localhost:9401/gasStationType/getPrice?gasStationId=${stationId}&gasTypeId=${gasTypeId}`,
	    method: 'GET',
	    header: {
	      'Authorization': uni.getStorageSync('Token')
	    },
	    success: (res) => {
	      console.log('api response', res)
	      if (res.data.code === 200) {
	        gasStations.value[index].price = res.data.data;
	        gasStations.value = [...gasStations.value];
	      } else {
	        console.error('获取油价失败:', res.data.msg);
	        gasStations.value[index].price = '--';
	        gasStations.value = [...gasStations.value];
	      }
	    },
	    fail: (error) => {
	      console.error('获取油价网络请求失败:', error);
	      gasStations.value[index].price = '--';
	      gasStations.value = [...gasStations.value];
	    }
	  });
	}
	
	function selectType(index) {
		selectedType.value = index;
		fetchGasStationsByType(index);
	}

	function goToMap(station) {
		uni.navigateTo({
			url: `/pages/index/reful/navigation/navigation?id=${station.id}`
		});
	}

	function goToStoreDetail(station) {
		uni.navigateTo({
			url: `/pages/index/reful/store/store?id=${station.id}`
		});
	}

	function map() {
		uni.navigateTo({
			url: "/pages/index/reful/map/map"
		})
	}
</script>
<style>
	.container {
		height: 200px;
		background: #007aff;
		padding-bottom: 20px;
	}

	.header-top {
		text-align: center;
		color: white;
		padding-top: 10px;
		font-size: 20px;
		font-weight: 500;
		letter-spacing: 1px;
	}

	.search-bar-wrapper {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px 15px 0 15px;
	}

	.search-bar {
		display: flex;
		align-items: center;
		background: #fff;
		border-radius: 20px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
		flex: 1;
		height: 40px;
		padding: 0 10px;
		border: 1.5px solid #e6e6e6;
	}

	.search-input {
		flex: 1;
		height: 36px;
		border: none;
		outline: none;
		background: transparent;
		font-size: 15px;
	}

	.search-icon {
		width: 22px;
		height: 22px;
		margin-left: 5px;
	}

	.map-mode-btn {
		margin-left: 10px;
		background: #ff9800;
		color: #fff;
		border-radius: 16px;
		padding: 0 16px;
		height: 32px;
		display: flex;
		align-items: center;
		font-size: 15px;
		font-weight: 500;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
	}

	.gasoline-types {
		display: flex;
		justify-content: space-between;
		margin: 18px 15px 0 15px;
	}

	.gasoline-type {
		background: #007aff;
		color: #fff;
		padding: 4px 18px;
		border-radius: 16px;
		font-size: 15px;
		font-weight: 400;
		margin-right: 6px;
		border: 1.5px solid #fff;
		transition: background 0.2s, color 0.2s;
	}

	.gasoline-type.selected {
		background: #0056c9;
		color: #fff;
		font-weight: 700;
		border: 1.5px solid #fff;
	}

	.gas-station-list {
		margin: 18px 15px 0 15px;
	}

	.gas-station-item {
		display: flex;
		background: #fff;
		border-radius: 14px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.07);
		margin-bottom: 18px;
		padding: 12px 12px 12px 12px;
		position: relative;
	}

	.gas-station-image {
		width: 70px;
		height: 52px;
		margin-right: 12px;
		border-radius: 8px;
		object-fit: cover;
	}

	.gas-station-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.name-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.name {
		font-size: 16px;
		font-weight: bold;
		color: #222;
		cursor: pointer;
	}

	.distance {
		color: #007aff;
		font-size: 14px;
		font-weight: 500;
	}

	.discount {
		display: flex;
		gap: 8px;
		margin: 6px 0 2px 0;
	}

	.discount-tag {
		background: #ff9800;
		color: #fff;
		border-radius: 10px;
		font-size: 12px;
		padding: 2px 8px;
		margin-right: 4px;
	}

	.business-hours {
		color: #888;
		font-size: 13px;
		margin-bottom: 2px;
	}

	.price {
		color: #ff3b30;
		font-size: 16px;
		font-weight: 600;
		margin-bottom: 2px;
	}

	.address {
		color: #333;
		font-size: 13px;
		margin-bottom: 2px;
	}

	.tiaozhuan {
		width: 18px;
		height: 18px;
		position: absolute;
		right: 16px;
		bottom: 16px;
	}
</style>